package com.neulogistics.contrib.warehouse.api.application.rpc;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.neulogistics.contrib.warehouse.domain.model.valueobject.Address;
import org.springframework.stereotype.Service;

@Service
public class GeographyService implements IGeographyService {
    @Override
    public String getLocation(Address address) {
        // 调用接口，获得经纬度
        HttpRequest request = HttpUtil.createGet("https://restapi.amap.com/v3/geocode/geo");
        request.form("address", address.getAddressString())
                .form("city", address.getCity())
                .form("key", System.getenv("AMAP_API_KEY"));

        HttpResponse response = request.execute();

        if (!response.isOk()){
            return null;
        }

        // 获取经纬度
        String body = response.body();
        JSONObject bodyJson = JSONUtil.parseObj(body);
        JSONArray geocodes = bodyJson.getJSONArray("geocodes");
        Object location = geocodes.getJSONObject(0).get("location");

        return location.toString();
    }
}
